package com.sphd.education.activitys;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.support.v7.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.android.volley.toolbox.StringRequest;
import com.sphd.education.R;
import com.sphd.education.adapter.CitysAdapter;
import com.sphd.education.base.BaseActivity;
import com.sphd.education.info.CityGpsInfo;
import com.sphd.education.info.CityInfo;
import com.sphd.education.info.EducationIntentKey;
import com.sphd.education.info.KeyWordInfo;
import com.sphd.education.modle.EducationUrl;
import com.sphd.education.utils.CharacterParser;
import com.sphd.education.utils.PinyinComparator;
import com.sphd.education.view.SideBar;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
/*
* 城市列表
* */
public class SearchCityActivity extends BaseActivity implements
        AMapLocationListener {
    @Bind(R.id.toolbar)
    Toolbar toolbar;

    @Bind(R.id.dialog)
    TextView dialog;
    @Bind(R.id.sidrbar)
    SideBar sidrbar;
    @Bind(R.id.city_listview)
    ListView cityListview;
    @Bind(R.id.gpscity_btn)
    Button gpscityBtn;
    @Bind(R.id.gpscity_textview)
    TextView gpscityTextview;
    private SearchView mSearchView;
    private Cursor myCursorcity;
    private SQLiteDatabase db;
    private String filepath;
    private Context context;
    private List<CityInfo> citylist;
    private CitysAdapter citysAdapter;
    private CityGpsInfo cityGpsInfo;//获取本地个人数据然后修改切换后的数据
    //定位的类
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
    private Intent intent;

    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private CharacterParser characterParser;
    private PinyinComparator pinyinComparator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_city);
        ButterKnife.bind(this);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        initView();
    }

    @Override
    public void initView() {
        context = SearchCityActivity.this;
        intent = new Intent();
        cityGpsInfo = DataSupport.findLast(CityGpsInfo.class);//查询出本地个人数据
        gpscityTextview.setText(cityGpsInfo.getLoacalcity());
        //实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PinyinComparator();
        citylist = new ArrayList<CityInfo>();
        filepath = "/data/data/" + context.getPackageName() + "/databases/china_province_city_zone.db";
        db = SQLiteDatabase.openDatabase(filepath, null, SQLiteDatabase.OPEN_READWRITE);
        myCursorcity = db.rawQuery("select * from T_City ", null);//是系统里的表
        if (myCursorcity != null) {
            citylist.clear();
            startManagingCursor(myCursorcity);
        }
        while (myCursorcity.moveToNext()) {
            CityInfo info = new CityInfo();
            info.setCityName(myCursorcity.getString(myCursorcity.getColumnIndex("CityName")));
            info.setCitySort(myCursorcity.getInt(myCursorcity.getColumnIndex("CitySort")));
            info.setProID(myCursorcity.getInt(myCursorcity.getColumnIndex("ProID")));
            //汉字转换成拼音
            String pinyin = characterParser.getSelling(myCursorcity.getString(myCursorcity.getColumnIndex("CityName")));
            String sortString = pinyin.substring(0, 1).toUpperCase();
            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                info.setSortLetters(sortString.toUpperCase());
            } else {
                info.setSortLetters("#");
            }

            citylist.add(info);
        }
        sidrbar.setTextView(dialog);
        // 根据a-z进行排序源数据
        Collections.sort(citylist, pinyinComparator);
        citysAdapter = new CitysAdapter(context, citylist);

        //设置右侧触摸监听
        sidrbar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = citysAdapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    cityListview.setSelection(position);
                }

            }
        });
        cityListview.setAdapter(citysAdapter);

        cityListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                //这里要利用adapter.getItem(position)来获取当前position所对应的对象
                ContentValues values = new ContentValues();
                values.put("qiecity", true);

                values.put("lastcity", cityGpsInfo.getOthercity());
                values.put("othercity", ((CityInfo) citysAdapter.getItem(position)).getCityName());
                DataSupport.update(CityGpsInfo.class, values, cityGpsInfo.getId());

                setResult(EducationIntentKey.SEARCHCITY, intent);
                finish();

            }
        });
        //实例化定位信息
        locationClient = new AMapLocationClient(context);
        locationOption = new AMapLocationClientOption();
        // 设置定位模式为高精度模式
        locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        // 设置定位监听
        locationClient.setLocationListener(this);

        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(EducationIntentKey.SEARCHCITY, intent);
                finish();//这是自带的箭头的返回的监听
            }
        });

    }

    @Override
    public void findViewById() {

    }

    @Override
    public void myNet() {

    }

    Handler mHandler = new Handler() {
        public void dispatchMessage(Message msg) {
            switch (msg.what) {
                //开始定位
                case EducationIntentKey.MSG_LOCATION_START:
                    break;
                // 定位完成
                case EducationIntentKey.MSG_LOCATION_FINISH:
                    String localCity;
                    AMapLocation loc = (AMapLocation) msg.obj;
                    if (loc.getCity().equals("")) {
                        localCity = "定位";
                        gpscityTextview.setText("定位失败再次获取");
                    } else {
                        localCity = loc.getCity();
                        gpscityTextview.setText(localCity);
                    }
                    ContentValues values = new ContentValues();
                    values.put("loacalcity", localCity);
                    values.put("lastcity", cityGpsInfo.getOthercity());
                    values.put("othercity", localCity);
                    values.put("qiecity", false);
                    values.put(" flush", true);
                    DataSupport.update(CityGpsInfo.class, values, cityGpsInfo.getId());
                    EducationUrl.showToast(context, "定位成功");
                    break;
                //停止定位
                case EducationIntentKey.MSG_LOCATION_STOP:

                    locationOption.setOnceLocation(false);
                    break;
                default:
                    break;
            }
        }


    };

    /***
     * 定位的代码
     */

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (null != aMapLocation) {
            Message msg = mHandler.obtainMessage();
            msg.obj = aMapLocation;
            msg.what = EducationIntentKey.MSG_LOCATION_FINISH;
            mHandler.sendMessage(msg);
        }

    }

    @OnClick(R.id.gpscity_btn)
    public void setOnClickGpsBtn() {

        // 启动定位
        locationClient.startLocation();
        locationOption.setOnceLocation(true);
        mHandler.sendEmptyMessage(EducationIntentKey.MSG_LOCATION_START);


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_searchcity, menu);
        mSearchView = (SearchView) MenuItemCompat.getActionView(menu
                .findItem(R.id.menu_search_city));
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                //
                citylist.clear();
                filepath = "/data/data/" + context.getPackageName() + "/databases/china_province_city_zone.db";
                db = SQLiteDatabase.openDatabase(filepath, null, SQLiteDatabase.OPEN_READWRITE);
                myCursorcity = db.rawQuery("select * from T_City where CityName LIKE '%" + newText + "%'", null);//是系统里的表
                if (myCursorcity != null) {
                    citylist.clear();
                    startManagingCursor(myCursorcity);
                }
                while (myCursorcity.moveToNext()) {
                    CityInfo info = new CityInfo();
                    info.setCityName(myCursorcity.getString(myCursorcity.getColumnIndex("CityName")));
                    info.setCitySort(myCursorcity.getInt(myCursorcity.getColumnIndex("CitySort")));
                    info.setProID(myCursorcity.getInt(myCursorcity.getColumnIndex("ProID")));
                    //汉字转换成拼音
                    String pinyin = characterParser.getSelling(myCursorcity.getString(myCursorcity.getColumnIndex("CityName")));
                    String sortString = pinyin.substring(0, 1).toUpperCase();
                    // 正则表达式，判断首字母是否是英文字母
                    if (sortString.matches("[A-Z]")) {
                        info.setSortLetters(sortString.toUpperCase());
                    } else {
                        info.setSortLetters("#");
                    }
                    citylist.add(info);
                }   // 根据a-z进行排序源数据
                if (citylist.size() > 0) {
                    Collections.sort(citylist, pinyinComparator);
                    citysAdapter.updateListView(citylist);
                } else {
                    return false;
                }
//                EducationUrl.showToast(context,citylist.get(0).getCityName());
                return true;
            }
        });
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.menu_search_city) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            setResult(EducationIntentKey.SEARCHCITY, intent);
            finish();//这是自带的箭头的返回的监听

            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
